<template>
    <BasicModal v-bind="$attrs" @register="registerModal" :title="displayModuleTitle" @ok="onButtonOkClick"
        :body-style="bodyStyle" width="500px">
        <BasicForm @register="registerForm" style="height:280px" />
    </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, unref, computed } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';

import { addOrUpdateChannelSchema } from '../exchangeChannel.data';
import { getChannel, addChannel, updateChannel } from '/@/api/qms/exchangeChannel'
import { queryEnumOption } from '/@/api/qms/exchangeData'
import { useMessage } from '/@/hooks/web/useMessage';
import { EnumDto } from '/@/api/qms/model/exchangeDataModel';
import { OperationTypeEnum } from '/@/enums/appEnum';
import { QcUnifyTransToChildProps } from '/#/QcUnify';
import { displayTitle } from '/@/utils/QcUnifyUtil';

const { createMessage } = useMessage();

export default defineComponent({
    name: 'AddOrUpdateChannel',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
        //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
        const operateType = ref(OperationTypeEnum.UN_KNOWN);

        const dataId = ref('');

        const bodyStyle = {
            height: '320px',
        };
        const qcUnifyProps = ref<QcUnifyTransToChildProps>();
        const [
            registerForm,
            { setFieldsValue, resetFields, validate, updateSchema },
        ] = useForm({
            labelWidth: 120,
            schemas: addOrUpdateChannelSchema,
            showActionButtonGroup: false,
            actionColOptions: {
                span: 24,
            },
        });

        /**
         * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
         */
        const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
            if (data != undefined && data != null) {
                let unrefData = unref(data);
                qcUnifyProps.value = unrefData;
                //接收父组件传递的数据
                if (unrefData?.operateType) {
                    //判断是否传入op属性
                    operateType.value = unrefData.operateType;
                }
                if (unrefData?.dataId) {
                    dataId.value = unrefData.dataId;
                }
            }
            resetFields(); //重置表单
            setModalProps({ confirmLoading: false });
            getComtype();
            // 如果是修改数据，根据传入的id获取数据后进行赋值
            if (operateType.value == OperationTypeEnum.EDIT) {
                getChannelById();
            }
        });

        let displayModuleTitle = computed(() => {
            return displayTitle(qcUnifyProps.value);
        });

        // 获取全部通信类型
        function getComtype() {
            queryEnumOption("CommunicationChannelTypeEnum").then((res: EnumDto) => {
                let Options = [];
                for (let d of res[0].options) {
                    // 这里要转number类型,因为获取全部参数类型请求回来的数据key为string,而接口为Number
                    Options.push({ value: Number(d.key), label: d.value ? d.value : d.key });
                }
                updateSchema({
                    field: 'comtype',
                    componentProps: {
                        options: Options,
                    },
                });
            })
        }
        function getChannelById() {
            getChannel(dataId.value)
                .then((res) => {
                    console.log('res', res);
                    setFieldsValue({
                        ...res,
                        direction: res.direction == 0 ? [] : res.direction == 3 ? [1, 2] : [res.direction]
                    });
                })
                .catch((ex) => {
                    console.log('catch ', ex);
                    createMessage.error(ex.msg);
                });
        }

        /**
         * 点击确认按钮，根据不同的op调用对应方法保存信息
         */
        async function onButtonOkClick() {
            const values = await validate();
            setModalProps({ confirmLoading: true });
            let param = values;
            if (!param.direction || param.direction.length < 1) param.direction = 0
            else param.direction = param.direction.reduce((result, curValue) => {
                return result | curValue;
            })
            //根据指定的操作类型分别进行提交数据和处理
            if (operateType.value == OperationTypeEnum.ADD) {
                //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
                try {
                    //调用接口进行保存
                    addChannel(param)
                        .then((res) => {
                            if (!res || Object.keys(res).length == 0) {
                                createMessage.success('保存成功。', 2);
                            }
                            opSuccess();
                        })
                        .catch((ex) => {
                            console.log('catch ', ex);
                            createMessage.error(ex.msg);
                        });
                } finally {
                    setModalProps({ confirmLoading: false });
                }
            } else if (operateType.value == OperationTypeEnum.EDIT) {
                //调用接口进行保存
                updateChannel(param)
                    .then((res) => {
                        if (!res || Object.keys(res).length == 0) {
                            createMessage.success('修改成功。', 2);
                        }
                        opSuccess();
                    })
                    .catch((ex) => {
                        console.log('catch ', ex);
                        // createMessage.error(ex.msg);
                    });
            } else {
                createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
            }
        }

        //操作成功后
        function opSuccess() {
            closeModal();
            emit('success');
        }

        return {
            operateType,
            displayModuleTitle,
            registerModal,
            getComtype,
            registerForm,
            getChannelById,
            onButtonOkClick,
            opSuccess,
            // getProjectValidDepts,
            bodyStyle,
        };
    },
});
</script>
